package 笔试;

import java.math.BigDecimal;
import java.util.Objects;

public class RedPackTest {
    // 最大不能超过最大金额的90%
    public static final BigDecimal BEST_PERCENT = new BigDecimal("0.9");
    // 单人每次最小抢到的金额，默认为1分钱,低于1分钱失去意义
    public static final BigDecimal ONE_PERSON_MIN_DRAW_AMOUNT = new BigDecimal("0.01");

    public static void solution(BigDecimal totalAmount, int persons) {
        BigDecimal minOpenAmount = new BigDecimal("0.01");
        BigDecimal leftAmount;

        for (Integer i = 0; i < persons; i++) {
            Integer remainPersons = persons - i - 1;
            if (remainPersons == 0) {
                // 最后一个人，直接把剩余金额返回
                leftAmount = totalAmount;
                System.out.println("第" + (i + 1) + "个人抢到:" + leftAmount + "元");
                break;
            }

            BigDecimal remainPersonNum = new BigDecimal(remainPersons);
            BigDecimal maxOpenAmount = totalAmount.multiply(BEST_PERCENT).setScale(2, BigDecimal.ROUND_UP);

            // 二倍均值法，使每个人的中奖金额都按均值概率分布
            BigDecimal doubleAverageAmount = totalAmount.divide(remainPersonNum, 2, BigDecimal.ROUND_UP)
                    .multiply(new BigDecimal("2")).setScale(2, BigDecimal.ROUND_UP);
            maxOpenAmount = doubleAverageAmount.compareTo(maxOpenAmount) < 0 ? doubleAverageAmount : maxOpenAmount;

            BigDecimal balance = totalAmount.subtract(maxOpenAmount.multiply(remainPersonNum));
            minOpenAmount = balance.compareTo(minOpenAmount) < 0 ? minOpenAmount : balance;

            //最大值，最小值里取随机数
            leftAmount = (maxOpenAmount.subtract(minOpenAmount)).multiply(new BigDecimal(Math.random()))
                    .setScale(2, BigDecimal.ROUND_UP);

            leftAmount = leftAmount.compareTo(minOpenAmount) < 0 ? minOpenAmount : leftAmount;

            // 每个人抢到红包后，红包内的剩余金额
            totalAmount = totalAmount.subtract(leftAmount);

            System.out.println("第" + (i + 1) + "个人抢到:" + leftAmount + "元");
        }
    }

    private static boolean checkNext(BigDecimal totalAmount, Integer personNum) {
        if (Objects.isNull(totalAmount) || totalAmount.compareTo(BigDecimal.ZERO) <= 0
                || Objects.isNull(personNum) || personNum < 1) {
            System.out.println("输入参数非法，请检查");
            return false;
        }

        // 红包总金额 >= 分配人数 * 每人最小中奖金额
        if (totalAmount.compareTo(ONE_PERSON_MIN_DRAW_AMOUNT.multiply(new BigDecimal(personNum))) < 0) {
            System.out.println("红包总金额不能小于(中奖人数*单人单次中奖金额)，请核对红包金额和发放人数");
            return false;
        }

        return true;
    }

    public static void main(String[] args) {

        BigDecimal totalAmount = new BigDecimal(100);
        Integer awardNum = 10;
        if (!checkNext(totalAmount, awardNum)) {
            return;
        }
        solution(totalAmount, awardNum);
    }
}